package team.yidong.fenda.serviceImpl;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.yidong.fenda.entity.*;
import team.yidong.fenda.repository.*;
import team.yidong.fenda.service.WxOrderService;
import team.yidong.fenda.payUtil.WxRefund;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by xuanlong on 2017/12/17.
 */
@Service
public class WxOrderServiceImpl implements WxOrderService {
    private final static Logger logger = LoggerFactory.getLogger(WxOrderService.class);

    @Autowired
    WxOrderRepository wxOrderRepository;
    @Autowired
    AnswerRepository answerRepository;
    @Autowired
    MasterRepository masterRepository;
    @Autowired
    MasterScoreRepository masterScoreRepository;
    @Autowired
    QuestionRepository questionRepository;
    @Autowired
    WxRefund wxRefund;

    @Transactional
    @Override
    public void addWxOrder(String out_trade_no, String appid, String bank_type, Integer total_fee, String time_end) {
        WxOrder wxOrder = wxOrderRepository.findByOutTradeNo(out_trade_no);
        wxOrder.setTimeEnd(time_end);
        wxOrder.setMoney(total_fee);
        wxOrder.setAppId(appid);
        wxOrder.setBankType(bank_type);
        wxOrder.setStatus("start");
        wxOrder.setHandleStatus("用户已付款");
        wxOrderRepository.save(wxOrder);

    }

    @Override
    public JSONObject findWxOrder(Integer offset, Integer limit, String userName, String hospitalName, String money, String finishDate, String endDate, String status) {
        Pageable pageable = new PageRequest(offset, limit, Sort.Direction.DESC, "id");
        Page<WxOrder> wxOrderPage = wxOrderRepository.findAll(new Specification<WxOrder>() {
            @Override
            public Predicate toPredicate(Root<WxOrder> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (userName != null && !userName.equals("")) {
                    Predicate p = criteriaBuilder.like(root.get("orderQuestion").get("user").get("name").as(String.class), "%" + userName + "%");
                    predicateList.add(p);
                }
                if (money != null && !money.equals("")) {
                    Predicate p = criteriaBuilder.equal(root.get("money").as(Integer.class), Integer.parseInt(money));
                    predicateList.add(p);
                }
                if (finishDate != null && !finishDate.equals("")) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date endDate = simpleDateFormat.parse(finishDate);
                        Predicate p = criteriaBuilder.greaterThanOrEqualTo(root.get("timeEnd").as(Date.class), endDate);
                        predicateList.add(p);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
                if (endDate != null && !endDate.equals("")) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date endDate1 = simpleDateFormat.parse(endDate);
                        Predicate p = criteriaBuilder.lessThanOrEqualTo(root.get("timeEnd").as(Date.class), endDate1);
                        predicateList.add(p);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
                if (hospitalName != null && !hospitalName.equals("")) {
                    Predicate p = criteriaBuilder.like(root.get("orderQuestion").get("user").get("hospital").get("name").as(String.class), "%" + hospitalName + "%");
                    predicateList.add(p);
                }
                if (status != null && !status.equals("")) {
                    Predicate p = criteriaBuilder.like(root.get("status").as(String.class), "%" + status + "%");
                    predicateList.add(p);
                }
                Predicate p1 = criteriaBuilder.notEqual(root.get("status").as(String.class), "mianfei");
                predicateList.add(p1);
                criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));
                return null;
            }
        }, pageable);
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(new String[]{"wxOrder", "questionURLSet", "answerList", "hospitalImgSet", "hospitalPermissionSet", "hospitalFieldList", "userSet", "masterList"});
        JSONObject jsonObject = JSONObject.fromObject(wxOrderPage, jsonConfig);
        String temp = "{\"total\":" + jsonObject.getString("totalElements") + ",\"rows\":" + jsonObject.getString("content") + "}";
        JSONObject j = JSONObject.fromObject(temp);

        return j;
    }

    @Override
    public List<WxOrder> findOrderNoAnswer() {

        return null;
    }

    @Transactional
    @Override
    public void wxOrderHandle() {
        //免费问题处理
        List<WxOrder> wxOrderFreeList = wxOrderRepository.findFreeQuestion();
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (WxOrder wxOrder : wxOrderFreeList) {
            try {
                long startTime = simpleDateFormat1.parse(wxOrder.getTimeEnd()).getTime();
                long nowTime = new Date().getTime();
                int days = (int) ((nowTime - startTime) / (1000 * 60 * 60 * 24));
                if (days >= 3) {
                    Question question = wxOrder.getOrderQuestion();
                    question.setAnswerStatus("过期无法回答");
                    questionRepository.save(question);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //收费问题处理
        List<WxOrder> wxOrderList = wxOrderRepository.findStartOrder();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (WxOrder wxOrder : wxOrderList) {
            try {
                long startTime = simpleDateFormat.parse(wxOrder.getTimeEnd()).getTime();
                long nowTime = new Date().getTime();
                int days = (int) ((nowTime - startTime) / (1000 * 60 * 60 * 24));
                if (days >= 3) {

                    if (wxOrder.getOrderQuestion().getAnswerList().size() == 0) {
                        //退款
                        logger.info("tuikuan");
                        wxRefund.wxRefund(wxOrder.getOutTradeNo(), wxOrder.getMoney().toString(), wxOrder.getMoney().toString());
                        wxOrder.setStatus("finish");
                        wxOrder.setHandleStatus("已退款");
                        wxOrderRepository.save(wxOrder);
                        Question question = wxOrder.getOrderQuestion();
                        question.setIsSolved("已关闭");
                        question.setAnswerStatus("过期无法回答");
                        questionRepository.save(question);
                    } else {
                        if (answerRepository.countStarAnswerByOrderId(wxOrder.getId()) == 0) {
                            logger.info("pingjun");
                            //平均分,保留两位小数
                            Question question = wxOrder.getOrderQuestion();
                            question.setAnswerStatus("过期无法回答");
                            questionRepository.save(question);
                            Integer moneyNum = wxOrder.getMoney();
                            double aveMoney = new BigDecimal((float) moneyNum / wxOrder.getOrderQuestion().getAnswerList().size()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            List<Answer> answerList = wxOrder.getOrderQuestion().getAnswerList();
                            for (Answer answer : answerList) {

                                MasterScore masterScore = answer.getMasterScore();
                                masterScore.setNum(aveMoney);
                                masterScore.setCreatDate(simpleDateFormat.format(new Date()));

                                masterScore.setStatus("未提现");
                                masterScoreRepository.save(masterScore);
                                wxOrder.setStatus("finish");
                                wxOrder.setHandleStatus("已平均分给专家");
                                wxOrderRepository.save(wxOrder);

                            }

                        } else {
                            logger.info("xingxingfen");
                            int starSum = 0;
                            //按照星星比例分
                            Question question = wxOrder.getOrderQuestion();
                            question.setAnswerStatus("过期无法回答");
                            questionRepository.save(question);
                            Integer moneyNum = wxOrder.getMoney();
                            List<Answer> answerList = wxOrder.getOrderQuestion().getAnswerList();
                            for (Answer answer : answerList) {
                                starSum += answer.getStarNum();
                            }
                            for (Answer answer : answerList) {
                                if (answer.getStarNum() != 0) {
                                    Double scoreNum = new BigDecimal((float) answer.getStarNum() / starSum).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * wxOrder.getMoney();

                                    MasterScore masterScore = answer.getMasterScore();
                                    masterScore.setNum(scoreNum);

                                    masterScore.setCreatDate(simpleDateFormat.format(new Date()));

                                    masterScore.setStatus("未提现");
                                    masterScoreRepository.save(masterScore);
                                    wxOrder.setStatus("finish");
                                    wxOrder.setHandleStatus("已按星级分给专家");
                                    wxOrderRepository.save(wxOrder);

                                }
                            }

                        }

                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }


        }
    }

}
